package weiyao.xinxidasai.Utils.FaceToken;

import com.baidu.aip.face.AipFace;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.HashMap;

public class FaceCompareUtils {

    private static final String APP_ID = FaceDetection.APP_ID;
    private static final String API_KEY = FaceDetection.API_KEY;
    private static final String SECRET_KEY = FaceDetection.SECRET_KEY;
    private static final String GROUP_ID = FaceRegistry.GROUP_ID;
    private static final int MIN_SCORE_THRESHOLD = 80; // 使用整数

    public static boolean compareFace(String userId, String faceToken) {
        AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);

        // 可选：设置超时时间（毫秒）
        client.setConnectionTimeoutInMillis(5000);
        client.setSocketTimeoutInMillis(10000);

        // 设置请求参数
        HashMap<String, Object> options = new HashMap<>();
        options.put("max_user_num", 1);
        options.put("match_threshold", MIN_SCORE_THRESHOLD);
        options.put("quality_control", "NORMAL");
        options.put("liveness_control", "NORMAL");
        options.put("user_id", userId); // 指定要对比的用户ID
        System.out.println("userId = " + userId);
        // 调用API
        JSONObject res = client.search(
                faceToken,
                "FACE_TOKEN",
                GROUP_ID,
                options
        );

        // 打印完整响应以便调试
        System.out.println("人脸对比API完整响应: " + res.toString(2)); // 使用缩进格式化输出

        // 检查错误码
        int errorCode = res.optInt("error_code", -1);
        if (errorCode != 0) {
            String errorMsg = res.optString("error_msg", "未知错误");
            System.err.println("人脸对比API错误: " + errorMsg + " (错误码: " + errorCode + ")");
            return false;
        }

        // 安全地获取result字段
        if (!res.has("result")) {
            System.err.println("API响应缺少result字段");
            return false;
        }

        // 解析结果
        JSONObject result = res.getJSONObject("result");
        JSONArray userList = result.optJSONArray("user_list");

        if (userList == null || userList.length() == 0) {
            System.out.println("人脸库中未找到匹配用户");
            return false;
        }

        JSONObject user = userList.getJSONObject(0);
        double score = user.optDouble("score", 0);
        String resultUserId = user.optString("user_id", "");

        System.out.println("匹配结果 - 用户ID: " + resultUserId + ", 相似度: " + score);

        // 验证匹配的用户ID和分数
        return score >= MIN_SCORE_THRESHOLD && userId.equals(resultUserId);
    }
}